<template>
  <div class="scheduled-tasks">
    <!-- 顶部操作栏 -->
    <div class="header-actions">
      <div class="left-actions">
        <el-button type="primary" @click="handleCreateTask">
          <i class="el-icon-plus"></i> 计划任务
        </el-button>
        <el-button-group>
          <el-button size="small">批量生效</el-button>
          <el-button size="small">批量失效</el-button>
          <el-button size="small">批量删除</el-button>
        </el-button-group>
      </div>
      <div class="right-search">
        <el-input
          v-model="searchQuery"
          placeholder="输入主机地址搜索"
          prefix-icon="el-icon-search"
          clearable
          size="small"
        >
        </el-input>
      </div>
    </div>

    <!-- 任务列表 -->
    <el-table
      :data="filteredTasks"
      style="width: 100%"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column prop="hostIp" label="主机地址" width="180">
        <template slot-scope="scope">
          <el-link type="primary" :underline="false">{{ scope.row.hostIp }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="schedule" label="策略详情" min-width="200">
        <template slot-scope="scope">
          <el-tag size="small" :type="getScheduleType(scope.row.scheduleType)">
            {{ scope.row.schedule }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="period" label="操作周期" width="120">
        <template slot-scope="scope">
          {{ scope.row.period }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="策略状态" width="100">
        <template slot-scope="scope">
          <el-tag
            :type="getStatusType(scope.row.status)"
            size="small"
            effect="dark"
          >
            <i :class="getStatusIcon(scope.row.status)"></i>
            {{ scope.row.status }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="note" label="备注" width="200">
        <template slot-scope="scope">
          {{ scope.row.note }}
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180">
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template slot-scope="scope">
          <el-button-group>
            <el-button
              type="text"
              size="small"
              @click="handleModify(scope.row)"
            >修改</el-button>
            <el-button
              type="text"
              size="small"
              @click="handleToggleStatus(scope.row)"
            >{{ scope.row.status === '生效' ? '暂停' : '生效' }}</el-button>
            <el-button
              type="text"
              size="small"
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </el-button-group>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
    </div>

    <!-- 任务配置对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
      :modal="false"
    >
      <el-form :model="taskForm" :rules="rules" ref="taskForm" label-width="100px">
        <el-form-item label="定时任务：">
          <span>{{ taskForm.name }}</span>
        </el-form-item>

        <el-form-item label="主机地址：">
          <span>{{ taskForm.hostIp }}</span>
        </el-form-item>

        <el-form-item label="任务类型：" prop="taskType">
          <el-radio-group v-model="taskForm.taskType">
            <el-radio label="开机">开机</el-radio>
            <el-radio label="关机">关机</el-radio>
            <el-radio label="重启">重启</el-radio>
          </el-radio-group>
          <div class="form-tip">(关机状态下，重启任务将按开机处理)</div>
        </el-form-item>

        <el-form-item label="执行周期：" prop="executionPeriod">
          <el-radio-group v-model="taskForm.executionPeriod">
            <el-radio label="执行一次">执行一次</el-radio>
            <el-radio label="重复执行">重复执行</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="开机时间：" prop="startTime">
          <el-date-picker
            v-model="taskForm.startTime"
            type="datetime"
            placeholder="请选择日期"
            style="width: 100%"
          >
          </el-date-picker>
        </el-form-item>

        <el-form-item label="任务生效时间：" prop="effectiveTime">
          <el-radio-group v-model="taskForm.effectiveTime">
            <el-radio label="立即生效">立即生效</el-radio>
            <el-radio label="自定义">自定义</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="任务截止时间：" prop="endTime">
          <el-radio-group v-model="taskForm.endTime">
            <el-radio label="无限期">无限期</el-radio>
            <el-radio label="自定义">自定义</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="备注：" prop="note">
          <el-input
            type="textarea"
            v-model="taskForm.note"
            :rows="3"
            placeholder="请输入备注信息"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog
      title="删除确认"
      :visible.sync="deleteDialogVisible"
      width="30%"
      :close-on-click-modal="false"
      :modal="false"
    >
      <div class="delete-confirm">
        <i class="el-icon-warning"></i>
        <p>确定要删除该计划任务吗？</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmDelete">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'ScheduledTasks',
  data() {
    return {
      searchQuery: '',
      currentPage: 1,
      pageSize: 10,
      total: 0,
      selectedTasks: [],
      dialogVisible: false,
      deleteDialogVisible: false,
      dialogTitle: '任务配置',
      currentTask: null,
      taskForm: {
        name: '主机定时开关机',
        hostIp: '39.99.234.143',
        taskType: '开机',
        executionPeriod: '执行一次',
        startTime: '',
        effectiveTime: '立即生效',
        endTime: '无限期',
        note: ''
      },
      rules: {
        taskType: [
          { required: true, message: '请选择任务类型', trigger: 'change' }
        ],
        executionPeriod: [
          { required: true, message: '请选择执行周期', trigger: 'change' }
        ],
        startTime: [
          { required: true, message: '请选择开机时间', trigger: 'change' }
        ]
      },
      tasks: [
        {
          hostIp: '39.98.137.75',
          schedule: '每天 07:00重启',
          period: '重复执行',
          status: '生效',
          note: '执行日常测试',
          createTime: '2024-02-29'
        },
        {
          hostIp: '39.98.90.201',
          schedule: '2024-1-26 15:07开机',
          period: '执行一次',
          status: '失效',
          note: '',
          createTime: '2024-01-26'
        },
        {
          hostIp: '39.98.90.201',
          schedule: '2024-10-9 18:50开机',
          period: '执行一次',
          status: '暂停',
          note: '',
          createTime: '2023-10-09'
        }
      ]
    }
  },
  computed: {
    filteredTasks() {
      let result = [...this.tasks]

      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase()
        result = result.filter(task =>
          task.hostIp.toLowerCase().includes(query)
        )
      }

      this.total = result.length
      return result
    }
  },
  methods: {
    handleCreateTask() {
      this.dialogTitle = '任务配置'
      this.dialogVisible = true
      this.currentTask = null
      this.$nextTick(() => {
        this.$refs.taskForm && this.$refs.taskForm.resetFields()
      })
    },
    handleModify(row) {
      this.dialogTitle = '修改任务'
      this.currentTask = row
      this.taskForm = {
        ...this.taskForm,
        name: '主机定时开关机',
        hostIp: row.hostIp,
        note: row.note
      }
      this.dialogVisible = true
    },
    handleToggleStatus(row) {
      const newStatus = row.status === '生效' ? '暂停' : '生效'
      this.$confirm(`确认要${newStatus}该任务吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        row.status = newStatus
        this.$message({
          type: 'success',
          message: '状态更新成功'
        })
      }).catch(() => {})
    },
    handleDelete(row) {
      this.currentTask = row
      this.deleteDialogVisible = true
    },
    confirmDelete() {
      if (this.currentTask) {
        const index = this.tasks.indexOf(this.currentTask)
        if (index > -1) {
          this.tasks.splice(index, 1)
        }
        this.$message({
          type: 'success',
          message: '删除成功'
        })
      }
      this.deleteDialogVisible = false
    },
    handleSelectionChange(selection) {
      this.selectedTasks = selection
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
    },
    handleCurrentChange(val) {
      this.currentPage = val
    },
    submitForm() {
      this.$refs.taskForm.validate((valid) => {
        if (valid) {
          // 处理表单提交
          this.$message({
            type: 'success',
            message: this.currentTask ? '任务更新成功' : '任务创建成功'
          })
          this.dialogVisible = false
        }
      })
    },
    getScheduleType(type) {
      return 'primary'
    },
    getStatusType(status) {
      const types = {
        '生效': 'success',
        '失效': 'danger',
        '暂停': 'warning'
      }
      return types[status] || 'info'
    },
    getStatusIcon(status) {
      const icons = {
        '生效': 'el-icon-check',
        '失效': 'el-icon-close',
        '暂停': 'el-icon-warning'
      }
      return icons[status] || 'el-icon-info'
    }
  }
}
</script>

<style scoped>
.scheduled-tasks {
  padding: 20px;
}

.header-actions {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.right-search {
  width: 250px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
}

.delete-confirm {
  text-align: center;
  padding: 20px 0;
}

.delete-confirm i {
  font-size: 48px;
  color: #E6A23C;
  margin-bottom: 20px;
}

.delete-confirm p {
  margin: 0;
  font-size: 16px;
  color: #606266;
}

:deep(.el-form-item__label) {
  font-weight: normal;
}

:deep(.el-radio) {
  margin-right: 20px;
}

:deep(.el-dialog__body) {
  padding: 20px 20px 0 20px;
}

@media screen and (max-width: 768px) {
  .scheduled-tasks {
    padding: 10px;
  }

  .header-actions {
    flex-direction: column;
    gap: 12px;
  }

  .left-actions {
    width: 100%;
  }

  .right-search {
    width: 100%;
  }

  .el-button-group {
    display: flex;
    width: 100%;
  }

  .el-button-group .el-button {
    flex: 1;
  }
}
</style>
